//
//  EQProvider.swift
//  EQQuestionBank
//
//  Created by 范伟健 on 2018/8/3.
//  Copyright © 2018年 FanWeiJian. All rights reserved.
//

import Foundation
import Moya
import HandyJSON
import RxSwift
import RxCocoa
import Result


let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider<EQService>.RequestResultClosure) -> Void in
    if var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 20
        closure(.success(urlRequest))
    } else {
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

let eqProvider = MoyaProvider<EQService>(requestClosure: timeoutClosure ,
                                         plugins: [RequestLoadingPlugin()])

enum EQService {
    case userLogin(name: String, password: String)
    case problemDistingguish(text: String)
    case problemInfo(id: String, type: String)
}


extension EQService : TargetType {
    var baseURL: URL{
        return URL(string: "http://111.230.166.91:8888/")!
    }
    
    var path: String {
        switch self {
        case .userLogin(_, _):
            return "user/login"
        case .problemDistingguish(_):
            return "search/problem/distinguish"
        case .problemInfo:
            return "search/problem/info"
        }
    }
    //各个接口的请求方式
    var method: Moya.Method {
        switch self {
        case .userLogin:
            return .post
        case .problemDistingguish:
            return .get
        case .problemInfo:
            return .get
        }
    }
    
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    //请求是否携带参数，如果需要参数
    var task: Task {
        switch self {
        case .userLogin(let name, let password):
            return .requestParameters(parameters: ["account": name, "password": password], encoding: URLEncoding.default)
        case .problemDistingguish(let text):
            return .requestParameters(parameters: ["text" : text], encoding: URLEncoding.default)
        case .problemInfo(let id, let type):
            return .requestParameters(parameters: ["id" : id,"type":type], encoding: URLEncoding.default)
        }
    }
    
    var headers: [String : String]? {
        return nil
    }
    
}


extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) throws -> T {
        let jsonString = String(data: data, encoding: .utf8)
        guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) else {
            throw MoyaError.jsonMapping(self)
        }
        return model
    }
}

//仿造Moya的RxSwift的mapJSON方法写的
extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
    public func mapModel<T: HandyJSON>(_ type: T.Type) -> Single<T> {
        return flatMap { response -> Single<T> in
            guard let model = try? response.mapModel(T.self) else{
                return Single.error(NSError.init(domain: "转换模型失败", code: 99, userInfo: nil))
            }
            return Single.just(model)
        }
    }
    
}

//与主功能接口脱离，降低了耦合度我们可以再这里处理请求的权限、token、loading等
public final class RequestLoadingPlugin: PluginType {
    public func willSend(_ request: RequestType, target: TargetType) {
        
    }
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        
    }
}


